using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using Thor.Models;
using Thor.WebRole.Services;
using Thor.Common;
using Thor.Domain;
using Thor.Domain.Configuration;

namespace Thor.WebRole.Controllers
{
    public abstract class AuthenticatedController : Controller
    {
        protected bool IsAuthenticated()
        {
            if (Request.Cookies != null && Request.Cookies.Count > 0)
            {
                return (from key in Request.Cookies.AllKeys
                        where key.ToUpper() == ".ASPXAUTH"
                        select key).Any();
            }
            else
                return false;
        }

        protected ActionResult CalendarAuthenticationRequired(string calendarEmail)
        {
            var calendar = GetCalendar(calendarEmail);

            if (calendar == null)
                return RedirectToAction("NotFound", "Calendar");
                
            if (!calendar.PublicCanView && !IsAuthenticated())
            {
                RouteValueDictionary d = new RouteValueDictionary();
                d.Add("ReturnUrl", string.Format("/calendars/{0}", calendarEmail));

                return RedirectToAction("Index", "Account", d);
            }

            return null;
        }

        protected ActionResult CurrentAvailabiltyAuthenticationRequired(string calendarEmail)
        {
            var calendar = GetCalendar(calendarEmail);

            if (calendar == null)
                return RedirectToAction("NotFound", "Calendar");

            if (!calendar.PublicCanView && !IsAuthenticated())
            {
                RouteValueDictionary d = new RouteValueDictionary();
                d.Add("ReturnUrl", string.Format("/currentavailability/{0}", calendarEmail));

                return RedirectToAction("Index", "Account", d);
            }

            return null;
        }

        protected ActionResult BookingAuthenticationRequired(string calendarEmail)
        {
            var calendar = GetCalendar(calendarEmail);

            if (calendar == null)
                return RedirectToAction("NotFound", "Calendar");

            if (!calendar.PublicCanBook && !IsAuthenticated())
            {
                RouteValueDictionary d = new RouteValueDictionary();
                d.Add("ReturnUrl", string.Format("/calendars/{0}", calendarEmail));

                return RedirectToAction("Index", "Account", d);
            }

            return null;
        }

        private Calendar GetCalendar(string calendarEmail)
        {
            var svc = new CalendarManagerDomainService();
            return svc.GetCalendar(calendarEmail);
        }
    }
}
